package com.pyue.eam.admin.utils;

import cn.hutool.core.collection.CollUtil;
import com.pyue.eam.common.data.tenant.TenantContextHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Consumer;

@Slf4j
@Component
@AllArgsConstructor
public class TenantHandleUtil {
    // private final SysTenantService sysTenantService;

    /**
     * 同步跑定时任务
     */
    public void multiTenantJobHandle(Consumer<Long> handler) {
        multiTenantJobHandleFlag(handler, false);
    }

    /**
     * 异步跑定时任务
     */
    public void multiTenantJobHandleAsync(Consumer<Long> handler) {
        multiTenantJobHandleFlag(handler, true);
    }

    /**
     * 任务处理
     */
    private void multiTenantJobHandleFlag(Consumer<Long> handler, Boolean asyncFlag) {
        try {
            final List<Long> allNeedJobTenantIds = getAllNeedJobTenantId();
            if (CollUtil.isNotEmpty(allNeedJobTenantIds)) {
                if (asyncFlag) {
                    // 异步处理
                    allNeedJobTenantIds.forEach(e -> {
                        TenantContextHolder.setTenantId(e);
                        AsyncUtil.execute(() -> handler.accept(e));
                    });
                } else {
                    // 同步处理
                    // CountDownLatch countDownLatch = new CountDownLatch(allNeedJobTenantIds.size());
                    allNeedJobTenantIds.forEach(e -> {
                        TenantContextHolder.setTenantId(e);
                        handler.accept(e);
                        // countDownLatch.countDown();
                    });
                    // countDownLatch.await();
                }
                log.info("任务完美完成");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 需要执行定时任务的租户id
     */
    private List<Long> getAllNeedJobTenantId() {
        // 先只算当前租户 todo 后期通过配置表获取
        return CollUtil.newArrayList(1712771837525516289L);

        // 目前只有租户6做定时任务
        /* return sysTenantService.getAllTenant().stream()
                .filter(e -> e.getNeedJob() != null && e.getNeedJob() == 1)
                .mapToLong(SysTenant::getId)
                .boxed()
                .collect(Collectors.toList()); */
    }

}
